package com.itheima.app.controller;

import com.itheima.app.interceptor.UserHolder;
import com.itheima.app.manager.UserManager;
import com.itheima.domain.db.User;
import com.itheima.domain.db.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

/**
 * @author zsk
 * @create 2022-03-13-16:12
 */
@RestController
public class UserController {


    @Autowired
    private UserManager userManager;

    //保存用户
    @PostMapping("/user/save")
    public ResponseEntity save(@RequestBody User user) {

        //返回状态码
        return userManager.save(user);//调用manager存储数据，返回主键id
    }

    //查询用户信息(根据phone)
    @GetMapping("/user/findByPhone")
    public ResponseEntity findByPhone(String phone) {
        //调用manager查询数据，返回结果
        return userManager.findByPhone(phone);

    }

    //发送验证码
    @PostMapping("/user/login")
    public void sendSms(@RequestBody Map<String, String> map) {
        //取出手机号
        String phone = map.get("phone");
        //调用manager
        userManager.sendSms(phone);
    }

    //登录/注册
    @PostMapping("/user/loginVerification")
    public ResponseEntity loginVerification(@RequestBody Map<String, String> param) {
        //获取手机号
        String phone = param.get("phone");

        //获取Redis数据
        String verificationCode = param.get("verificationCode");
        //调用manager
        return userManager.loginVerification(phone, verificationCode);
    }

    //用户首次登录补全信息
    @PostMapping("/user/loginReginfo")
    public void loginReginfo(@RequestBody UserInfo userInfo, @RequestHeader("Authorization") String token) {
        //调用manager
        userManager.loginReginfo(userInfo, token);

    }

    //头像上传
    @PostMapping({"/user/loginReginfo/head", "/users/header"})
    public ResponseEntity loginReginfoHead(MultipartFile headPhoto, @RequestHeader("Authorization") String token) throws IOException {
        //调用manager
        return userManager.loginReginfoHead(headPhoto, token);
    }

    //查询用户信息
    @GetMapping("/users")
    public ResponseEntity findUserInfoVo(Long userId) {
        //前端传递id时，根据id查询
        if (userId != null) {
            return userManager.findUserInfoVo(userId);
        } else {
            //前端不传递解析token,获取用户id
            User user = UserHolder.get();
            return userManager.findUserInfoVo(user.getId());
        }
    }

    //更新用户信息
    @PutMapping("/users")
    public void putUserInfo(@RequestBody UserInfo userInfo) {
        //调用manager修改
        userManager.putUserInfo(userInfo);
    }


}
